package com.qianbao.qianbaobusiness.ui.invoice;

import android.graphics.PointF;
import android.net.Uri;
import android.os.Bundle;
import android.view.View;
import android.view.animation.Animation;
import android.view.animation.AnimationUtils;
import android.view.animation.LinearInterpolator;
import android.widget.Button;
import android.widget.ImageView;
import android.widget.LinearLayout;
import android.widget.TextView;

import com.baseandroid.event.ContractListEvent;
import com.baseandroid.mvp.BaseMvpActivity;
import com.bumptech.glide.Glide;
import com.bumptech.glide.request.target.SimpleTarget;
import com.bumptech.glide.request.transition.Transition;
import com.davemorrissey.labs.subscaleview.ImageSource;
import com.davemorrissey.labs.subscaleview.ImageViewState;
import com.davemorrissey.labs.subscaleview.SubsamplingScaleImageView;
import com.qianbao.qianbaobusiness.R;
import com.qianbao.qianbaobusiness.json.ContractListBean;
import com.qianbao.qianbaobusiness.json.ContractSignSuccessBean;
import com.qianbao.qianbaobusiness.ui.widget.dialog.ConfirmDialog;
import com.qianbao.qianbaobusiness.ui.widget.dialog.SignContractDialog;

import org.greenrobot.eventbus.EventBus;

import java.io.File;
import java.util.ArrayList;
import java.util.List;

import butterknife.BindView;
import butterknife.OnClick;

import static com.qianbao.qianbaobusiness.ui.widget.dialog.SignContractDialog.SIGN_FAIL_STATE;
import static com.qianbao.qianbaobusiness.ui.widget.dialog.SignContractDialog.SIGN_PROCESS_STATE;

/**
 * @author: Routee
 * @date 2018/6/20
 * @mail wangc4@qianbaocard.com
 * ------------1.本类由Routee开发,阅读、修改时请勿随意修改代码排版格式后提交到git。
 * ------------2.阅读本类时，发现不合理请及时指正.
 * ------------3.如需在本类内部进行修改,请先联系Routee,若未经同意修改此类后造成损失本人概不负责。
 */
public class ContractDetailActivity extends BaseMvpActivity<ContractDetailView, ContractDetailPresenter> implements ContractDetailView {

    @BindView(R.id.tv_title)
    TextView                  mTvTitle;
    @BindView(R.id.iv_loading)
    ImageView                 mIvLoading;
    @BindView(R.id.ll_loading)
    LinearLayout              mLlLoading;
    @BindView(R.id.pv)
    SubsamplingScaleImageView mPv;
    @BindView(R.id.bt)
    Button                    mBt;

    private int                               mCurrentItem = 0;
    private int                               mFirstItem   = 0;
    private List<ContractListBean.ResultBean> mList        = new ArrayList<>();
    private Animation          mAnimation;
    private ConfirmDialog      mConfirmDialog;
    private SignContractDialog mDialog;
    /*ImageLoader.Callback myImageLoaderCallback = new ImageLoader.Callback() {
        @Override
        public void onCacheHit(File image) {
        }

        @Override
        public void onCacheMiss(File image) {
        }

        @Override
        public void onStart() {
            startLoading();
        }

        @Override
        public void onProgress(int progress) {
        }

        @Override
        public void onFinish() {
            stopLoading();
        }

        @Override
        public void onSuccess(File image) {
        }

        @Override
        public void onFail(Exception error) {
        }
    };*/

    @Override
    protected int getLayoutId() {
        // BigImageViewer.initialize(PickviewGlideImageLoader.with(Global.getContext()));
        return R.layout.activity_contract_detail;
    }

    @Override
    protected void initInject() {
        getActivityComponent().inject(this);
    }

    @Override
    protected void setupView() {
        initBundle();
        initView();
    }

    private void initView() {
        mTvTitle.setText("合作协议");
        if (mList.get(mCurrentItem).getState() == 1) {
            mBt.setVisibility(View.VISIBLE);
        } else {
            mBt.setVisibility(View.GONE);
        }
        showContract();
    }

    private void showContract() {
        if (null == mList || mList.size() == 0) {
            return;
        }
        Glide.with(ContractDetailActivity.this)
                .load(Uri.parse(mList.get(mCurrentItem % mList.size())
                                        .getContractImgPath()))
                .downloadOnly(new SimpleTarget<File>() {
                    @Override
                    public void onResourceReady(File resource, Transition<? super File> transition) {
                        mPv.setImage(ImageSource.uri(resource.getAbsolutePath()), new ImageViewState(1.0f, new PointF(0, 0), 0));
                    }
                });
    }

    private void initBundle() {
        Bundle b = getIntent().getExtras();
        if (b != null) {
            mCurrentItem = b.getInt("currentItem");
            mList = (List<ContractListBean.ResultBean>) b.getSerializable("list");
        }
        mFirstItem = mCurrentItem;
    }

    @Override
    protected void setupData(Bundle savedInstanceState) {

    }

    @OnClick({R.id.iv_back_toolbar, R.id.bt})
    public void onViewClicked(View view) {
        switch (view.getId()) {
            case R.id.iv_back_toolbar:
                finish();
                break;
            case R.id.bt:
                if (mBt.getText().equals("完成")) {
                    finish();
                    return;
                } else if (mBt.getText().equals("下一份合同")) {
                    showCurrentPage();
                    return;
                }
                showConfirmDialog();
                break;
            default:
                break;
        }
    }

    private void showCurrentPage() {
        mTvTitle.setText("合作协议");
        showContract();
        mBt.setText("签字");
    }

    private void showConfirmDialog() {
        mConfirmDialog = new ConfirmDialog.Builder(this).setContentText("请您审慎阅读并选择取消或确认本协议。如您点击“确认”，即视为您已充分阅读、理解、同意、接受本协议全部内容")
                                 .setCanceledOnTouchOutside(false)
                                 .setConfirmListener(new ConfirmDialog.Builder.ConfirmClickListener() {
                                     @Override
                                     public void click(boolean b) {
                                         mConfirmDialog.dismiss();
                                         if (b) {
                                             startSignContract();
                                         }
                                     }
                                 })
                                 .create();
        mConfirmDialog.show();
    }

    private void startSignContract() {
        if (mDialog == null) {
            mDialog = new SignContractDialog(this);
        }
        mDialog.setState(SIGN_PROCESS_STATE);
        mDialog.show();
        if (mList != null && mList.size() > 0 && mCurrentItem < mList.size()) {
            getPresenter().signContract(mList.get(mCurrentItem)
                                                .getContractId(), mList.get(mCurrentItem).getbUserId());
        }
    }

    private void startLoading() {
        mPv.setVisibility(View.GONE);
        mLlLoading.setVisibility(View.VISIBLE);
        if (mAnimation == null) {
            mAnimation = AnimationUtils.loadAnimation(this, R.anim.view_img_loading);
        }
        mAnimation.setRepeatCount(Animation.INFINITE);
        mAnimation.setInterpolator(new LinearInterpolator());
        mAnimation.setDuration(1000L);
        mIvLoading.startAnimation(mAnimation);
    }

    private void stopLoading() {
        mAnimation.cancel();
        mIvLoading.clearAnimation();
        mLlLoading.setVisibility(View.GONE);
        mPv.setVisibility(View.VISIBLE);
    }

    @Override
    public void signContractSuccess(ContractSignSuccessBean result) {
        EventBus.getDefault().post(new ContractListEvent());
        if (mDialog.isShowing()) {
            mDialog.dismiss();
        }
        mList.get(mCurrentItem % mList.size()).setContractImgPath(result.getContractImgPath());
        showContract();
        jumpToNextPage();
    }

    @Override
    public void signContractFailed() {
        if (mDialog != null && mDialog.isShowing()) {
            mDialog.setState(SIGN_FAIL_STATE);
        }
    }

    private void jumpToNextPage() {
        mCurrentItem += 1;
        if (mCurrentItem < mFirstItem + mList.size()) {
            if (mList.get(mCurrentItem % mList.size()).getState() == 1) {
                mBt.setText("下一份合同");
            } else {
                jumpToNextPage();
            }
        } else {
            mBt.setText("完成");
        }
    }
}

